package com.hitqz.robot.biz.flow.component.agv;

import com.alibaba.fastjson.JSONObject;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.Tickets;
import com.hitqz.robot.biz.flow.domain.constant.FlowConstant;
import com.hitqz.robot.biz.service.RobotService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

/**
 * @author xupkun
 * @date 2025/5/13
 */
@Slf4j
@LiteflowComponent(value = "NotifyUpdateAgvTask", name = "[轮对/轮轴]通知上位机真正执行的AGV")
@AllArgsConstructor
public class NotifyUpdateAgvTask extends NodeComponent {

    private final RestTemplate restTemplate;

    private final RobotService robotService;

    @Override
    public void process() throws Exception {
        String uri = this.getCmpData(cn.hutool.json.JSONObject.class).get(FlowConstant.NODE_CUSTOM_INFO_MAP.get(this.getNodeId()).getParamNames().get(0), String.class).trim();
        FlowContextDto dto = this.getRequestData();
        FlowPatrolPreAndEndTicketsDto ticketsDto = JSONObject.parseObject(dto.getTicketsTask()
                .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
        String auto = ticketsDto.getModalData().get("auto")== null ? "0":
                String.valueOf(ticketsDto.getModalData().get("auto"));
        if (auto.equals("0")) {
            log.info("半自动任务:");
            return ;
        }
        Tickets task = dto.getTickets();
        String taskCode = task.getTaskNo();
        Robot robot = robotService.getDefaultRobot();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sbID", robot.getRobotSn());
        jsonObject.put("taskCode", taskCode);
        try {
            HttpEntity<String> strEntity = new HttpEntity<String>(jsonObject.toString(), headers);
            log.info("{} 通知真正执行的AGV接口式:{}", uri, strEntity);
            String result = restTemplate.postForObject(uri, strEntity, String.class);
            log.info("响应结果：{}", result);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!resultJson.getBoolean("ret")) {
                log.error("\n通知真正执行的AGV接口失败:\nurl:{}\nrequest:{}\nresponse:{}", uri, strEntity, result);
                throw new RuntimeException("通知真正执行的AGV接口失败!uri:" + uri);
            }
        } catch (Exception e) {
            log.error("通知真正执行的AGV接口失败!{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
}
